package com.start.security;

import com.start.common.details.BaseUserDetails;
import com.start.security.handler.IStartPermissionLoad;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

@Component("pas")
public class StartPermissionAuthService {

    @Autowired
    private StartUserPermissionTools userPermissionTools;

    /**
     * 判断是否有菜单权限
     *
     * @param permissions 权限编码
     * @return
     */
    public boolean hasPermission(String... permissions) {
        if (permissions == null || permissions.length < 1) {
            return false;
        }
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (principal == null)
            return false;
        BaseUserDetails userDetails = (BaseUserDetails) principal;
        final IStartPermissionLoad handler = userPermissionTools.getHandlerByUserType(userDetails);
        if (handler == null) return true;
        return handler.hasPermission(userDetails, permissions);
    }


    /**
     * 判断是否有角色权限
     *
     * @param roleCodes 角色编码
     * @return
     */
    public boolean hasRoles(String... roleCodes) {
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (principal == null) {
            return false;
        }
        BaseUserDetails userDetails = (BaseUserDetails) principal;
        final IStartPermissionLoad handler = userPermissionTools.getHandlerByUserType(userDetails);
        return handler.hasRoles(userDetails, roleCodes);
    }
}
